"use client";

import { useEffect, useState } from "react";
import { getSessionById, SessionDetail } from "@/lib/api/session";
import { getPersona } from "@/lib/api/persona";
import { useAuth } from "@/lib/auth/context";

export function useSessionDetail(sessionId?: string) {
  const { loading: authLoading, user } = useAuth();
  const [data, setData] = useState<SessionDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!sessionId || authLoading || !user) return;
    const controller = new AbortController();
    setLoading(true);
    (async () => {
      try {
        const res = await getSessionById(sessionId, controller.signal);
        if ((!res.skill || !res.personaSnapshot) && res.personaId) {
          try {
            const persona = await getPersona(res.personaId, controller.signal);
            setData({
              ...res,
              skill: res.skill ?? (Array.isArray(persona.skills) ? persona.skills[0] : undefined),
              personaSnapshot: res.personaSnapshot ?? {
                id: persona.id,
                name: persona.name,
                displayName: persona.displayName,
                voiceId: persona.voiceId,
                language: persona.language,
                skills: persona.skills,
                avatar: persona.avatar,
              },
            });
            setError(null);
            return;
          } catch {
          }
        }
        setData(res);
        setError(null);
      } catch (e: any) {
        setError(e?.message ?? "Loading failed");
      } finally {
        setLoading(false);
      }
    })();
    return () => controller.abort();
  }, [sessionId, authLoading, user]);

  return { data, loading, error };
}